var nav = getByClass("navi")[0],
	tab = nav.getElementsByTagName("a"),
	navbg = getByClass("nav_bg")[0],
	index = 0;

for(var i = 0; i < tab.length; i++) {
	tab[i].index = i;
}

//移入，可以用onmouseover
nav.onmouseenter = function(e) {
	nav.onmousemove = function(e) {
		var e = e || window.event,
			target = e.target || e.srcElement;

		if(target.nodeName.toLocaleLowerCase() == "a") { //事件委托
			fontTurnBlack();
			target.style.color = "white";
			animate(navbg, {
				"left": [target.offsetLeft],
				"width": [target.offsetWidth]
			});
		}
	}
}

nav.onclick = function(e) {
	var e = e || window.event,
		target = e.target || e.srcElement;

	if(target.nodeName.toLocaleLowerCase() == "a") {
		index = target.index;
	}
}

//移出，使用onmouseout（冒泡）会导致一些问题不能用，onmouseleave不存在冒泡
nav.onmouseleave = function(e) {
	clearInterval(navbg.timer);
	fontTurnBlack();
	tab[index].style.color = "white";
	animate(navbg, {
		"left": [tab[index].offsetLeft],
		"width": [tab[index].offsetWidth]
	});
}

//遍历导航项，字体置为黑色
function fontTurnBlack() {
	for(var i = 0; i < tab.length; i++) {
		tab[i].style.color = "#3c3c3c";
	}
}

//通过className查找，支持IE6+
function getByClass(className, parent) {
	var res = [],
		parent = parent || document,
		allTag = parent.getElementsByTagName("*");

	for(var i = 0; i < allTag.length; i++) {
		var clsn = allTag[i].className.match('(^|\\s)' + className + '(\\s|$)');
		if(clsn) {
			res.push(allTag[i]);
		}
	}
	return res;
}

//获取非行间样式
function getStyle(obj, attr) {
	if(obj.currentStyle) {
		return obj.currentStyle[attr];
	}
	return getComputedStyle(obj, false)[attr];

}

//动画
function animate(obj, json, fn) {
	clearInterval(obj.timer);
	obj.timer = setInterval(function() {
		var bool = true;

		for(var attr in json) {
			var current = (attr == "opacity") ? Math.round(getStyle(obj, attr) * 100) : (parseInt(getStyle(obj, attr)) || 0),
				target = json[attr][0] || json[attr],
				steps = json[attr][1] || 10,
				speed = (target - current) / steps;

			speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
			current = current + speed;

			if(attr == 'opacity') {
				obj.style.filter = 'alpha(opacity:' + current + ')';
				obj.style[attr] = current / 100;

			} else {
				obj.style[attr] = current + 'px';
			}
			//所有动画结束
			if(target !== current) {
				bool = false;
			}
		}

		if(bool) {
			clearInterval(obj.timer);
			if(fn) {
				fn();
			}
		}
	}, 1000 / 60);
}